package com.example.demo.commom;

import com.example.demo.entity.Userinfo;
import io.jsonwebtoken.*;
import jdk.internal.org.objectweb.asm.tree.analysis.Value;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:龙宝
 * Date:2023-11-07
 * Time:9:23
 */
public class JWTUtils {
    private static final long EXPIERS = 1000 * 60 * 60 * 24; //设置为一天

    private static final String SECRET = "xiaolong";//设置密钥，每个公司都不一样~

    /**
     * 使用JWT生成token
     * @param id
     * @param username
     * @return
     */
    public static String getTWTToken(Integer id,String username) {
        String JWTToken = Jwts.builder()
                //JWT头
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")

                //JWT主体
                //这三个为可选
                .setSubject("guli-user") //主题
                .setIssuedAt(new Date()) //创建时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIERS)) // 过期时间

                //主题中存储用户信息的部分
                .claim("id",id)
                .claim("username",username)

                //设置签名哈希，防伪标志
                .signWith(SignatureAlgorithm.HS256,SECRET)
                .compact();
        return JWTToken;
    }

    /**
     * 验证token是否存在  +  有效
     * @param JWTToken
     * @return
     */
    public static boolean checkToken(String JWTToken) {
        if(!StringUtils.hasLength(JWTToken)) {
            return false;
        }
        try{
            Jwts.parser().setSigningKey(SECRET).parseClaimsJws(JWTToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 验证token是否存在  +  有效
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String token = request.getHeader("token");
            if(!StringUtils.hasLength(token)) {
                return false;
            }
            Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据token获取id
     * @param request
     * @return
     */
    public static Userinfo getMemberIdByJwtToekn(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Userinfo userinfo = new Userinfo();
        if(!StringUtils.hasLength(token)) {
            return userinfo;
        }
        try{
            //解析token
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
            Integer id = Integer.valueOf(claimsJws.getBody().getId());
            userinfo.setId(id);
            return userinfo;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
